package com.superb.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.superb.common.core.annotation.SuperbDataScope;
import com.superb.common.core.annotation.SuperbRestMapping;
import com.superb.common.core.model.Result;
import com.superb.common.database.vo.BatchId;
import com.superb.common.redis.key.KeyType;
import com.superb.common.redis.key.RedisKey;
import com.superb.common.redis.utils.RedisUtils;
import com.superb.system.api.dto.MenuItem;
import com.superb.system.api.dto.Options;
import com.superb.system.api.dto.RolePerms;
import com.superb.system.api.dto.TopAndSideMenu;
import com.superb.system.api.emuns.MenuType;
import com.superb.system.api.entity.SystemPermission;
import com.superb.system.api.entity.SystemUser;
import com.superb.system.api.vo.Distribution;
import com.superb.system.api.vo.PermissionAction;
import com.superb.system.service.SystemPermissionService;
import com.superb.system.service.SystemUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.Duration;
import java.util.List;

/**
 * 系统菜单权限表;(system_permission)表控制层
 * @Author: ajie
 * @CreateTime: 2024-5-15
 */
@SuperbDataScope
@SuperbRestMapping("/systemPermission")
@Tag(name = "系统菜单权限表接口")
@ApiSupport(author = "阿杰：ajie20999@163.com", order = 5)
public class SystemPermissionController {

    @Resource
    private SystemPermissionService systemPermissionService;

    @Resource
    private SystemUserService userService;

    @GetMapping("query/{type}")
    @ApiOperationSupport(order = 1)
    @SaCheckPermission("system:menu:select")
    @Operation(summary = "菜单查询", description = "权限: system:menu:select<br>", parameters = {
            @Parameter(name = "type", description = "菜单类型：0侧边栏菜单；1顶部菜单；2中台菜单", required = true)
    })
    public Result<List<SystemPermission>> query(@PathVariable String type) {
        List<SystemPermission> result = systemPermissionService.menuTree(type, false);
        return Result.success(result);
    }

    @GetMapping("parentMenu/{type}")
    @ApiOperationSupport(order = 1)
    @SaCheckPermission("system:menu:select")
    @Operation(summary = "父级菜单", description = "权限: system:menu:select<br>")
    public Result<List<Options>> parentMenu(@PathVariable String type) {
        List<Options> result = systemPermissionService.parentMenu(type);
        return Result.success(result);
    }

    @PostMapping("insert")
    @ApiOperationSupport(order = 2)
    @SaCheckPermission("system:menu:insert")
    @Operation(summary = "新增信息", description = "权限: system:menu:insert<br>")
    public Result<Boolean> insert(@RequestBody @Validated SystemPermission systemPermission) {
        if (systemPermissionService.save(systemPermission)) {
            return Result.success();
        }
        return Result.error();
    }

    @PostMapping("update")
    @ApiOperationSupport(order = 3)
    @SaCheckPermission("system:menu:update")
    @Operation(summary = "修改信息", description = "权限: system:menu:update<br>")
    public Result<Boolean> update(@RequestBody @Validated SystemPermission systemPermission) {
        if (systemPermissionService.updateById(systemPermission)) {
            return Result.success();
        }
        return Result.error();
    }

    @GetMapping("info/{id}")
    @ApiOperationSupport(order = 4)
    @Operation(summary = "根据id获取信息", parameters = {
            @Parameter(name = "id", description = "业务主键", required = true, in = ParameterIn.PATH)
    })
    public Result<SystemPermission> getInfo(@PathVariable String id) {
        return Result.success(systemPermissionService.getById(id));
    }

    @GetMapping("remove/{id}")
    @ApiOperationSupport(order = 5)
    @SaCheckPermission("system:menu:update")
    @Operation(summary = "根据id删除", description = "权限: system:menu:update<br><font style='color: #1890FF'>假删除，会进入回收站</font>", parameters = {
            @Parameter(name = "id", description = "业务主键", required = true, in = ParameterIn.PATH)
    })
    public Result<Boolean> removeById(@PathVariable String id) {
        if (systemPermissionService.update(Wrappers.<SystemPermission>lambdaUpdate().set(SystemPermission::getDel, 1).eq(SystemPermission::getId, id))) {
            return Result.success();
        }
        return Result.error();
    }

    @GetMapping("delQuery")
    @ApiOperationSupport(order = 6)
    @SaCheckPermission({"system:menu:select", "system:menu:delete"})
    @Operation(summary = "回收站", description = "权限: <br>同时拥有system:menu:select、system:menu:delete")
    public Result<List<SystemPermission>> delQuery() {
        List<SystemPermission> result = systemPermissionService.delPage();
        return Result.success(result);
    }

    @PostMapping("recovery")
    @ApiOperationSupport(order = 7)
    @SaCheckPermission({"system:menu:update", "system:menu:delete"})
    @Operation(summary = "根据id恢复删除的数据", description = "权限: <br>同时拥有system:menu:update、system:menu:delete")
    public Result<Boolean> recovery(@RequestBody @Validated BatchId batchId) {
        if (systemPermissionService.recoveryByBatchId(batchId.getId())) {
            return Result.success();
        }
        return Result.error();
    }

    @PostMapping("delete")
    @ApiOperationSupport(order = 8)
    @SaCheckPermission("system:menu:delete")
    @Operation(summary = "根据id彻底删除", description = "权限: system:menu:delete<br><font style='color: red'>真删除，数据无法恢复</font>")
    public Result<Boolean> delete(@RequestBody @Validated BatchId batchId) {
        if (systemPermissionService.deleteByBatchId(batchId.getId())) {
            return Result.success();
        }
        return Result.error();
    }

    @GetMapping("menu/{type}")
    @ApiOperationSupport(order = 5)
    @Operation(summary = "获取当前登录人的顶部菜单", parameters = {
            @Parameter(name = "type", description = "菜单类型", required = true, in = ParameterIn.PATH)
    })
    public Result<List<MenuItem>> menu(@PathVariable MenuType type) {
        SystemUser user = userService.getInfoById(StpUtil.getLoginId().toString());
        RedisKey key = new RedisKey(KeyType.PER, "menuCache:" + user.getId());
        List<MenuItem> menuItems = RedisUtils.build().hash().getNullSet(key, type.name(),
                () -> systemPermissionService.menuList(user.getId(), type),
                redis -> redis.hash().get(key, type.name())
        );
        return Result.success(menuItems);
    }

    @GetMapping("topAndSideMenu")
    @ApiOperationSupport(order = 6)
    @Operation(summary = "获取当前登录人的顶部菜单和侧边栏菜单")
    public Result<TopAndSideMenu> topAndSideMenu() {
        SystemUser user = userService.getInfoById(StpUtil.getLoginId().toString());
        RedisKey key = new RedisKey(KeyType.TIME, Duration.ofMinutes(60), "menuCache:" + user.getId());
        TopAndSideMenu menuItems = RedisUtils.build().value().getNullSet(key, () -> {
            TopAndSideMenu menu = new TopAndSideMenu();
            if (user.getSuperb() == 1) {
                menu.setTop(systemPermissionService.menuList(null, MenuType.top));
                menu.setSide(systemPermissionService.menuList(null, MenuType.side));
            } else {
                menu.setTop(systemPermissionService.menuList(user.getId(), MenuType.top));
                menu.setSide(systemPermissionService.menuList(user.getId(), MenuType.side));
            }
            return menu;
        }, redis -> redis.value().get(key));
        return Result.success(menuItems);
    }

    @GetMapping("permissionList/{menuId}")
    @Operation(summary = "菜单权限", parameters = {
            @Parameter(name = "menuId", description = "菜单id", required = true, in = ParameterIn.PATH)
    })
    public Result<List<SystemPermission>> permissionList(@PathVariable String menuId) {
        LambdaQueryWrapper<SystemPermission> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SystemPermission::getParentId, menuId).eq(SystemPermission::getMenuType, 2);
        lqw.select(SystemPermission::getId, SystemPermission::getRemarks, SystemPermission::getSort, SystemPermission::getName, SystemPermission::getPerms);
        List<SystemPermission> list = systemPermissionService.list(lqw);
        return Result.success(list);
    }

    @PostMapping("permissionAction")
    @SaCheckPermission("system:permission:manage")
    @Operation(summary = "菜单权限操作", description = "权限：system:permission:manage")
    public Result<Boolean> permissionInsert(@RequestBody @Validated PermissionAction action) {
        SystemPermission permission = new SystemPermission();
        BeanUtils.copyProperties(action, permission);
        permission.setMenuType(2);
        if (systemPermissionService.saveOrUpdate(permission)) {
            return Result.success();
        }
        return Result.error();
    }

    @GetMapping("rolePermission/{roleId}")
    @SaCheckPermission("system:permission:manage")
    @Operation(summary = "获取角色权限", description = "权限：system:permission:manage")
    public Result<RolePerms> rolePermission(@PathVariable String roleId) {
        return Result.success(systemPermissionService.getRolePermission(roleId));
    }

    @PostMapping("permission/distribution")
    @SaCheckPermission("system:permission:distribution")
    @Operation(summary = "权限分配", description = "权限：system:permission:distribution")
    public Result<Boolean> distribution(@RequestBody @Validated Distribution distribution) {
        // 1. 先删除角色权限
        if (systemPermissionService.deletePermsByRoleId(distribution.getRoleId())) {
            // 2. 将新权限添加
            systemPermissionService.distribution(distribution);
            return Result.success("权限分配成功！");
        }
        return Result.error("权限分配操作失败！");
    }

    @PostMapping("permission/addDistribution")
    @SaCheckPermission("system:permission:distribution")
    @Operation(summary = "勾选权限时分配", description = "权限：system:permission:distribution")
    public Result<Boolean> addDistribution(@RequestBody @Validated Distribution distribution) {
        if (systemPermissionService.distribution(distribution)) {
            return Result.success("权限分配成功！");
        }
        return Result.error("权限分配操作失败！");
    }

    @PostMapping("permission/removeDistribution")
    @SaCheckPermission("system:permission:distribution")
    @Operation(summary = "取消勾选时删除权限", description = "权限：system:permission:distribution")
    public Result<Boolean> removeDistribution(@RequestBody @Validated Distribution distribution) {
        // 1. 先删除角色权限
        if (distribution.getMenuIds().size() > 0) {
            systemPermissionService.deletePermsByRoleId(distribution.getRoleId(), distribution.getMenuIds().get(0));
        }
        if (distribution.getPermissionIds().size() > 0) {
            systemPermissionService.deletePermsByRoleId(distribution.getRoleId(), distribution.getPermissionIds().get(0));
        }
        return Result.success("取消权限成功！");
    }

}